#include "fsa.h"
#include <QDebug>

Fsa::Fsa(QObject *parent) :
    QObject(parent)
{
    savetype = Fsa::local;
    connect(&fsw,SIGNAL(directoryChanged(QString)),SLOT(findNewFiles(QString)));
//    qDebug() << "started\n";

}

void Fsa::setIFolder(QString fldn) {
//    qDebug() << fldn;
    QDir fld(fldn);
    if (fld.exists()) {
        if (!fsw.directories().isEmpty()) fsw.removePaths(fsw.directories());
        fsw.addPath(fldn);
        ifldn = fldn;
        ifld = fld;
        count = ifld.count();
        fls = ifld.entryList();
    } else {
        emit IFolderMising();
    }
}

void Fsa::setOFolder(QString fld) {
//    qDebug() << fld;
    ofldn = fld;
    ofld = QDir(fld);
    if (!ofld.exists()) ofld.mkpath(fld);
}

void Fsa::findNewFiles(QString) {
    ifld.refresh();

    if (ifld.count() > count) {

//        qDebug() << "nov file" << ifld.count() << count ;
        int d = ifld.count() - count;
        for (int i=ifld.count()-1; i>=0 && d>=0; --i) {
            if (!fls.contains(ifld.entryList()[i])) {
                cpfls.append(ifld.entryList()[i]);
                handleFile(ifld.entryList()[i]);
                --d;
            }
        }

    }
//    else {
//        qDebug() << "njama novi" << ifld.count() << count;
//    }

//    qDebug() << ifld.entryList();
//    qDebug() << cpfls;

//    for (int i=0; i < cpfls.count(); ++i ) handleFile(cpfls[i]);

    count = ifld.count();
    fls = ifld.entryList();
}

void Fsa::handleFile(QString fln) {
//    qDebug() << fln;
    if (savetype == Fsa::local) {
        QTimer* tm = new QTimer(this);
        tm->setInterval(2048);
        tm->setSingleShot(true);
        connect(tm, SIGNAL(timeout()), SLOT(moveFile()) );
        tm->start();
    } else {
        qDebug() << "remote store is not implemented yet";
    }
}


void Fsa::moveFile() {
    mtx.lock();

    if (!cpfls.isEmpty()) {
        QString fln = cpfls.takeFirst();
//        qDebug() << ifld.absoluteFilePath(fln) << "->" << ofld.absoluteFilePath(fln);
        QFile fl(ifld.absoluteFilePath(fln));
        if (!fl.copy(ofld.absoluteFilePath(fln))) {
            qDebug() << fl.error() << fl.errorString();
        }
    }

    QTimer *tm = qobject_cast<QTimer*>(sender());
    tm->deleteLater();

    mtx.unlock();
}

void Fsa::setSaveType(savetypes svt) {
    savetype = svt;
}

Fsa::savetypes Fsa::SaveType() {
    return savetype;
}

QString Fsa::IFolder() {
    return ifldn;
}


QString Fsa::OFolder() {
    return ofldn;
}
